package com.eh.command.controller;

import com.eh.command.command.Command;
import com.eh.command.controller.ext.Slot;
import com.eh.reflectoin.MethodInvokerUtil;
import com.eh.reflectoin.dto.MethodInvokerRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Stack;

/**
 * Created by David on 2016/4/30.
 */
public class RemoteController {
    private volatile static RemoteController remoteController;

    private static Logger logger = LoggerFactory.getLogger(RemoteController.class);

    private Slot[] slots;
    private Stack<MethodInvokerRequest> operationHistories;

    private RemoteController() {
        slots = new Slot[7];
        for (int i = 0; i < 7; i++) {
            slots[i] = new Slot();
        }
        operationHistories = new Stack<>();
    }

    public static RemoteController getInstance() {
        if (remoteController == null) {
            synchronized (RemoteController.class) {
                if (remoteController == null) {
                    remoteController = new RemoteController();
                }
            }
        }
        return remoteController;
    }

    public void setCommand(int slotIndex, Command command) {
        slots[slotIndex].bind(command);
        logger.info("[按钮{}绑定:{}]", slotIndex, command);
    }

    public void press(int slotIndex) {
        slots[slotIndex].pressed();
    }

    public void removeCommand(int slotIndex) {
        if (slots[slotIndex].isUsed()) {
            slots[slotIndex].clear();
        }
        logger.info("[按钮{}移除:{}]", slotIndex, slots[slotIndex].getCommandName());
    }

    public void addOperationHistory(MethodInvokerRequest methodInvokerRequest) {
        operationHistories.add(methodInvokerRequest);
    }

    public void undo() {
        if (operationHistories.size() > 0) {
            operationHistories.pop();
        }
        if (operationHistories.size() > 0) {
            MethodInvokerUtil.invoke(operationHistories.peek());
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < slots.length; i++) {
            if (slots[i].isUsed()) {
                sb.append(String.format("[按钮%s绑定:%s]%n", i, slots[i].getCommandName()));
            }
        }
        return sb.toString();
    }
}
